package com.codemasters.programa;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.sql.SQLException;
import java.util.UUID;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;

import com.codemasters.datos.BaseDeDatos;
import com.codemasters.datos.Factura;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.Color;
import javax.swing.JSpinner;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;

public class frmCompra extends JFrame {

	
	JLabel lblPrecio;
	JLabel lblCodigoCliente;
	JComboBox comboBoxArticulos;
	JLabel lblIdProduct;
	String codCliente;
	String fechaIngresada2;
	JLabel lblNombreCliente;
	private JTextField txtCantidadProducto;
	private JLabel lblCodigoCliente_1;
	
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frmCompra frame = new frmCompra(null, null, null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public frmCompra(String codigCliete , String nombreCliente, final String fechaIngresada) throws SQLException, ClassNotFoundException {
		
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 474, 401);
		
		
		this.codCliente = codigCliete;        //Recibiendo los datos
		this.fechaIngresada2 = fechaIngresada;//que entraron por paramentros a la clase
		
		JLabel lblNomClienteCompra = new JLabel(nombreCliente);
		lblNomClienteCompra.setForeground(Color.RED);
		JLabel lblCodigoCliente = new JLabel(nombreCliente);
		lblCodigoCliente.setForeground(Color.RED);
		
		lblNombreCliente = new JLabel(codigCliete);
		lblNombreCliente.setForeground(Color.RED);
		
		JLabel lblCodigo = new JLabel("Codigo Cliente:");
		JLabel lblCliente = new JLabel("Cliente:");
		JLabel lblCantidad = new JLabel("Cantidad:");
		JLabel lblCodigoProducto = new JLabel("Codigo Producto:");
		JLabel lblCodigoFactura = new JLabel("Codigo Factura:");
		JLabel lblFecha = new JLabel("Fecha:");
		JLabel lblFechaIngresada = new JLabel(fechaIngresada2);//imprime la fecha que se ingreso
		JLabel lblArticulo = new JLabel("Articulo:");
		JLabel lblPrecioArticulo = new JLabel("Precio Articulo:");
		lblCodigoCliente_1 = new JLabel();
		lblPrecio = new JLabel();
		lblPrecio.setForeground(Color.RED);
		lblIdProduct = new JLabel();
		lblIdProduct.setForeground(Color.RED);
		
		
		comboBoxArticulos = new JComboBox();
	
		
		txtCantidadProducto = new JTextField();
		txtCantidadProducto.setColumns(10);
		
		JButton btnCancelar = new JButton("Cancelar");
		JButton btnAgregarCarrito = new JButton("Agregar Al Carrito");
		
		
		String codigoFactura = UUID.randomUUID().toString(); //generando codigo aleatorio de letras y numeros para evitar duplicacion de facturas
		String[] codigoFinal =  codigoFactura.split("-");   //como devuelve una cantidad grade le hago split para solo tener los primeros 8 digitos
		
		final JLabel lblRandom = new JLabel(codigoFinal[0]);  //asignando el codigo de la factura al label   
		lblRandom.setForeground(Color.BLUE);
			
		
		
		
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
		btnAgregarCarrito.addActionListener(new ActionListener() 
		{
			
			public void actionPerformed(ActionEvent arg0)
			{
				
		
				try {
					
					//Creando un objeto tipo factura y pasando los datos de la compra
					Factura factura = new Factura(lblIdProduct.getText(), txtCantidadProducto.getText(), lblPrecio.getText(), "ADMINISTRADOR", codCliente);
					
					//registrando la compra en la base de datos
					BaseDeDatos.registrarVenta(factura, lblRandom.getText(), fechaIngresada);
					
					 try {
						   
						    //para confirmar si va a agregar mas producto al carrito
				            if (JOptionPane.showConfirmDialog(null, "Desea agregar mas producto a su carrito?") == JOptionPane.YES_OPTION)
				            {
				            	lblPrecio.setText("");
				            	lblIdProduct.setText("");
				            	txtCantidadProducto.setText("");
				                return;         
				            }
				            else
				            {
				            	
				            	dispose();//Cerrando la ventana compra
				            	JOptionPane.showMessageDialog(null, "GRACIAS POR SU COMPRA!!!");
				            	
				            }
				           
				        } catch (Exception ex) {
				            JOptionPane.showMessageDialog(null, ex.getMessage());
				        } 
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
			}
		});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
		

		BaseDeDatos.llenarCombobox(comboBoxArticulos); //Llenando combobox que mostrara los articulos disponibles
		
		
	    comboBoxArticulos.addItemListener(new ItemListener() //Escuchador para cuando se seleccione un articulo de el combobox
	    {
			public void itemStateChanged(ItemEvent evt) {
				
				if(evt.getStateChange() == ItemEvent.SELECTED)
				{

				    try 
				    {
						//Asignando los demas datos de el articulo seleccionado a los label
						BaseDeDatos.seleccionItemCombobox(comboBoxArticulos.getSelectedItem().toString(), lblPrecio, lblIdProduct);
						
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
			}
		});
		
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		
		
		
		
		
		
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(23)
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
							.addGroup(groupLayout.createSequentialGroup()
								.addComponent(lblPrecioArticulo)
								.addGap(18)
								.addComponent(lblPrecio))
							.addGroup(groupLayout.createSequentialGroup()
								.addComponent(lblCodigoProducto)
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(lblIdProduct))
							.addGroup(groupLayout.createSequentialGroup()
								.addComponent(lblArticulo)
								.addGap(18)
								.addComponent(comboBoxArticulos, GroupLayout.PREFERRED_SIZE, 118, GroupLayout.PREFERRED_SIZE))
							.addGroup(groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
									.addComponent(btnAgregarCarrito)
									.addGroup(groupLayout.createSequentialGroup()
										.addComponent(lblCantidad)
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addComponent(txtCantidadProducto, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE)))
								.addGap(57)
								.addComponent(btnCancelar, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE)))
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(lblCliente)
									.addPreferredGap(ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
									.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addComponent(lblCodigoCliente_1, Alignment.TRAILING)
										.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
											.addComponent(lblNomClienteCompra)
											.addGap(19))))
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(lblCodigoFactura)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(lblRandom)))
							.addGap(73)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(lblCodigo)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(lblNombreCliente))
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(lblFecha)
									.addGap(18)
									.addComponent(lblFechaIngresada)))))
					.addContainerGap(97, Short.MAX_VALUE))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNombreCliente)
						.addComponent(lblCodigo)
						.addComponent(lblCodigoCliente_1)
						.addComponent(lblCliente)
						.addComponent(lblNomClienteCompra))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblRandom)
						.addComponent(lblCodigoFactura)
						.addComponent(lblFecha)
						.addComponent(lblFechaIngresada))
					.addGap(18)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblArticulo)
						.addComponent(comboBoxArticulos, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(33)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblPrecioArticulo)
						.addComponent(lblPrecio))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblCodigoProducto)
						.addComponent(lblIdProduct))
					.addGap(40)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblCantidad)
						.addComponent(txtCantidadProducto, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(65)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnAgregarCarrito)
						.addComponent(btnCancelar))
					.addContainerGap(55, Short.MAX_VALUE))
		);
		getContentPane().setLayout(groupLayout);
	}
}
